package com.leetcode.partition1;

import java.util.*;

/**
 * @author `RKC`
 * @date 2021/8/13 10:49
 */
public class LC39组合总和 {

    public static List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(candidates);
        backtracking(candidates, target, 0, result, new ArrayList<>(), 0);
        return result;
    }

    public static void main(String[] args) {
        int[] candidates = { 2, 3, 6, 7 };
        int target = 7;
        System.out.println(combinationSum(candidates, target));
    }

    private static void backtracking(int[] candidates, int target, int startIndex, List<List<Integer>> result, List<Integer> path, int sum) {
        if (sum > target) return;
        if (sum == target) {
            result.add(new ArrayList<>(path));
            return;
        }
        //剪枝，如果sum+candidates[i]>target就没必要进行操作了，但要进行排序
        for (int i = startIndex; i < candidates.length && sum + candidates[i] <= target; i++) {
            path.add(candidates[i]);
            backtracking(candidates, target, i, result, path, sum + candidates[i]);
            path.remove(path.size() - 1);
        }
    }
}
